package com.diorsunion.hedge.bo.datasync.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.diorsunion.hedge.base.ExternalApiBaseTest;
import com.diorsunion.hedge.base.NetBaseTest;
import com.diorsunion.hedge.bo.net.DataFetcher;
import com.diorsunion.hedge.bo.net.XueQiuDataFetcher;
import com.diorsunion.hedge.util.LogUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.*;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * 生成ETF股票的SQL
 * Created by harley-dog on 2015/12/29.
 */
public class StockInsertSQLGenerator extends ExternalApiBaseTest {
    @Test
    public void test() throws URISyntaxException, IOException {
        BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("etf.sql"),"utf-8"));
        DataFetcher dataFetcher = new XueQiuDataFetcher();
        String cookie = dataFetcher.getCookie(new URI("http://xueqiu.com"));
        String time =  String.valueOf(System.currentTimeMillis());
        for(int page=1;page<=5;page++){
            URIBuilder uriBuilder = new URIBuilder("http://xueqiu.com/stock/cata/stocktypelist.json")
                    .setParameter("_", time)
                    .setParameter("page", String.valueOf(page))
                    .setParameter("size", "90")
                    .setParameter("order", "asc")
                    .setParameter("type", "1")
                    .setParameter("orderby", "symbol");
            URI uri = uriBuilder.build();
            HttpGet httpget = new HttpGet(uri);
            httpget.addHeader("Cookie", cookie);
            httpget.addHeader("Host", "xueqiu.com");
            httpget.addHeader("RA-Sid", "3CB01D6F-20140709-112055-4c09cf-c1239f");
            LogUtil.info("Executing request " + httpget.getRequestLine());
            CloseableHttpClient httpclient = HttpClients.custom().build();
            CloseableHttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            String s = EntityUtils.toString(entity);
            JSONObject obj = JSON.parseObject(s);
            JSONArray chartlist = (JSONArray) obj.get("stocks");
            for (int i = 0; chartlist != null && i < chartlist.size(); i++) {
                StringBuilder sql = new StringBuilder("INSERT into stock(code,name,exchange,type,url,total_shares,market_capital) VALUES(");

                JSONObject jsonObject = chartlist.getJSONObject(i);

                String name = jsonObject.getString("name");
                String code = jsonObject.getString("code");
                URIBuilder uriBuilder_stock = new URIBuilder("http://xueqiu.com/v4/stock/quote.json?code=CHIE&_=1451359812072")
                        .setParameter("_", time)
                        .setParameter("code", code);
                URI uri_stock = uriBuilder_stock.build();
                HttpGet httpget_stock = new HttpGet(uri_stock);
                httpget_stock.addHeader("Cookie", cookie);
                httpget_stock.addHeader("Host", "xueqiu.com");
                httpget_stock.addHeader("RA-Sid", "3CB01D6F-20140709-112055-4c09cf-c1239f");
                LogUtil.info("Executing request " + httpget_stock.getRequestLine());
                CloseableHttpClient httpclient_stock = HttpClients.custom().build();
                CloseableHttpResponse response_stock = httpclient_stock.execute(httpget_stock);
                HttpEntity entity_stock = response_stock.getEntity();
                String s_stock = EntityUtils.toString(entity_stock);
                JSONObject obj_stock = null;
                try{
                    obj_stock = JSON.parseObject(s_stock).getJSONObject(code);
                }catch (Exception e){
                    e.printStackTrace();
                }
                if(obj_stock==null){
                    continue;
                }
                long market_Capital = obj_stock.containsKey("marketCapital") && obj_stock.getString("marketCapital").trim().length()>0?new BigDecimal(obj_stock.getString("marketCapital")).longValue():0;
                long totalShares = obj_stock.containsKey("totalShares") && obj_stock.getString("totalShares").trim().length()>0?obj_stock.getLong("totalShares"):0;
                double close = obj_stock.containsKey("close") && obj_stock.getString("close").trim().length()>0?obj_stock.getDouble("close"):0;
                String exchange = obj_stock.containsKey("exchange")?obj_stock.getString("exchange"):"";
                if(totalShares==0 && close!=0){
                    totalShares = new BigDecimal(market_Capital).divide(new BigDecimal(close),BigDecimal.ROUND_HALF_UP).longValue();
                }
                sql
                        .append("\'" + code + "\'")
                        .append(",\'" + name + "\'")
                        .append(",\'"+exchange+"\'")
                        .append(",\'E\'")
                        .append(",\'http://xueqiu.com/s/"+code+"\'")
                        .append(","+totalShares)
                        .append(","+market_Capital)
                        .append(");");
                System.out.println(sql);
                writer.write(sql.toString());
                writer.newLine();
                httpclient_stock.close();
            }
            httpclient.close();
        }
        writer.close();
    }
}
